const app = getApp();
//引入插件：微信同声传译
const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();
 
Page({
  data: {
    p:0,
    texts:['你的牙齿动是因为你正在换牙，这是每个人成长过程中的自然现象。就像小树苗长成大树，旧的叶子会掉落一样，你的乳牙会掉落，然后长出更坚固的恒牙','牙齿有点黄很正常，因为牙齿表面有一层保护层。只要我们每天刷牙，保持口腔卫生，牙齿就会健健康康的。如果想要牙齿更漂亮，可以定期去牙医那里洗牙'],//模拟文本
    //语音
    recordState: false, //录音状态
    content:'',//用户发送内容
    AIcontent:'',//AI发送内容
    src:'',
      // 当前登录者信息
      login: {
          id: '2023',
          user: '大猪蹄子',
          avatar: 'https://gitee.com/ToBugCoding/my-photo-bed/raw/master/imgurl/%E5%85%AC%E5%8F%B8%E5%B0%8F%E7%A8%8B%E5%BA%8F%E9%87%8D%E5%86%99/tooth3/child.png'
      },
      xiaochi: {
        id: '2022',
        user: 'AI小齿',
        avatar: 'https://gitee.com/ToBugCoding/my-photo-bed/raw/master/imgurl/%E5%85%AC%E5%8F%B8%E5%B0%8F%E7%A8%8B%E5%BA%8F%E9%87%8D%E5%86%99/tooth3/%E8%8A%B1%E8%8A%B1.png'
    },
      // 聊天信息
      chatList: [
          {
          },
      ],
  },
  onLoad() {
      this.scrollToBottom();
  },
  // 输入监听
  inputClick(e) {
      this.setData({
          content: e.detail.value
      })
  },
  //小齿发送数据
  xiaochisend(){
    var that = this;
      var list = this.data.chatList;
      // 获取当前时间
      var date = new Date();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minu = date.getMinutes();
      var now1 = month < 10 ? '0' + month : month;
      var now2 = day < 10 ? '0' + day : day;
      // 组装数据
      var msg = {
          msgId: this.data.xiaochi.id,
          nickname: this.data.xiaochi.user,
          avatar: this.data.xiaochi.avatar,
          message: this.data.AIcontent,
          type: 'text',
          date: now1 + '-' + now2 + ' ' + hour + ':' + minu
      }
      this.setData({
          chatList: list.concat(msg)
      }, () => {
          that.scrollToBottom();
          that.setData({
            AIcontent: ''
        })
      })
  },
  // 用户发送数据
  sendClick() {
      var that = this;
      var list = this.data.chatList;
      // 获取当前时间
      var date = new Date();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minu = date.getMinutes();
      var now1 = month < 10 ? '0' + month : month;
      var now2 = day < 10 ? '0' + day : day;
      // 组装数据
      var msg = {
          msgId: this.data.login.id,
          nickname: this.data.login.user,
          avatar: this.data.login.avatar,
          message: this.data.content,
          type: 'text',
          date: now1 + '-' + now2 + ' ' + hour + ':' + minu
      }
      this.setData({
          chatList: list.concat(msg)
      }, () => {
          that.scrollToBottom();
      })
      wx.request({
        url: 'https://www.aistomatology.cn/wx/AiCommute',
        method: 'POST',
        header:{  
          'content-type':'application/x-www-form-urlencoded'
        },
        data: {
          content:that.data.content
        },
        success:function(savedata){
          var dis = savedata.data
          console.log( dis.detail.output.choices[0].message.content)
          that.setData({
            AIcontent: dis.detail.output.choices[0].message.content,
          })
          that.xiaochisend();
          that.wordYun();
        },
     })
  },
  // 滑动到最底部
  scrollToBottom() {
      setTimeout(() => {
          wx.pageScrollTo({
              scrollTop: 200000,
              duration: 3
          });
      }, 600)
  },
  back:function(){
    wx.switchTab({
      url: '/pages/head/head',
    })
  },
  onReady:function(){
        //创建内部 audio 上下文 InnerAudioContext 对象。
        this.innerAudioContext = wx.createInnerAudioContext();
        this.innerAudioContext.onError(function (res) {
          console.log(res);
          wx.showToast({
            title: '语音播放失败',
            icon: 'none',
          })
        }) 
  },
  onLoad: function (options) {
    //识别语音
    this.setData({
      AIcontent:"有任何问题请吩咐我",
      chatList:[]
    })
    this.initRecord();
    this.wordYun(0);
    this.xiaochisend();
  },
  //识别语音 -- 初始化
  initRecord: function () {
    const that = this;
    // 有新的识别内容返回，则会调用此事件
    manager.onRecognize = function (res) {
      console.log(res)
    }
    // 正常开始录音识别时会调用此事件
    manager.onStart = function (res) {
      console.log("成功开始录音识别", res)
    }
    // 识别错误事件
    manager.onError = function (res) {
      console.error("error msg", res)
    }
    //识别结束事件
    manager.onStop = function (res) {
      console.log('..............结束录音')
      console.log('录音临时文件地址 -->' + res.tempFilePath); 
      console.log('录音总时长 -->' + res.duration + 'ms'); 
      console.log('文件大小 --> ' + res.fileSize + 'B');
      console.log('语音内容 --> ' + res.result);
      if (res.result == '') {
        wx.showModal({
          title: '提示',
          content: '听不清楚，请重新说一遍！',
          showCancel: false,
          success: function (res) {}
        })
        return;
      }
      var text =res.result;
      //text发送给服务器
      that.setData({
        content: text
      })
      that.sendClick();
    }
  },
  //语音  --按住说话
  touchStart: function (e) {
    this.setData({
      recordState: true  //录音状态
    })
    // 语音开始识别
    manager.start({
      lang: 'zh_CN',// 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
    })
  },
  //语音  --松开结束
  touchEnd: function (e) {
    var that=this;
    this.setData({
      recordState: false
    })
    // 语音结束识别
    manager.stop();
  }





  //转语音
  // 文字转语音
  ,
  wordYun:function (e) {
    var that = this;
    var content=this.data.AIcontent;
    plugin.textToSpeech({
      lang: "zh_CN",
      tts: true,
      content: content,
      success: function (res) {
        console.log(res);
        console.log("succ tts", res.filename);
        that.setData({
          src: res.filename
        })
        that.yuyinPlay();
 
      },
      fail: function (res) {
        console.log("fail tts", res)
      }
    })
  },
  
  //播放语音
  yuyinPlay: function (e) {
    if (this.data.src == '') {
      console.log(暂无语音);
      return;
    }
    this.innerAudioContext.src = this.data.src //设置音频地址
    this.innerAudioContext.play(); //播放音频
  },
})